<?php

namespace app\admin\controller\kefu;

use app\common\controller\Backend;
use app\admin\model\kefu\Config as ConfigModel;

class Config extends Backend
{
    /**
     * 模型对象
     * @var object
     * @phpstan-var ConfigModel
     */
    protected object $model;

    protected array $fieldType = [
        'array' => ['send_goods_identity', 'send_orders_identity'], // 出入库时数组类型装换
    ];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new ConfigModel();
    }

    public function index(): void
    {
        $data   = $this->model->select();
        $config = [];
        foreach ($data as $k => $v) {
            if (in_array($v['name'], $this->fieldType['array'])) {
                $v['value'] = explode(',', $v['value']);
                $v['value'] = array_filter($v['value']);
            }
            $config[$v['name']] = $v['value'];
        }
        $this->success('', [
            'data' => $config,
        ]);
    }

    public function save(): void
    {
        $data = $this->request->post();
        foreach ($data as $k => $v) {
            if (in_array($k, $this->fieldType['array'])) {
                $v = implode(',', $v);
            }
            $this->model->where('name', $k)->update(['value' => $v]);
        }
        $this->success('当前页配置保存成功！');
    }
}